#include "IMITab.h"

IMITab::IMITab()
{
	this->preIndex=-1;
	this->currentIndex=-1;
	this->isInternal=false;
	m_iTouchBeganListener=NULL;
	m_ifnTouchBeganSelector=NULL;
}

void IMITab::addButton(IMIButton * imiButton)
{
	imiButton->onTouchBegan(this,SEL_TouchHandler(&IMITab::changeTab));
	this->m_tab.push_back(imiButton);	
}

void IMITab::setTab(int tabIndex)
{
	//CCLog("setTab..0..............................................%i",tabIndex);
	if(tabIndex<0||tabIndex>=int(this->m_tab.size())) return;
	//CCLog("setTab..1..............................................%i",tabIndex);
	if(currentIndex==tabIndex) return;
	//CCLog("setTab..2..............................................%i",tabIndex);
	if(currentIndex==-1&&preIndex==-1)
	{
		//CCLog("setTab..3..............................................%i",tabIndex);
		currentIndex=tabIndex;
		preIndex=tabIndex;
		m_tab[currentIndex]->setSelect(true);
		m_tab[currentIndex]->setTouchEnabled(false);
	}else
	{
		//CCLog("setTab..4..............................................%i",tabIndex);
		preIndex=currentIndex;
		currentIndex=tabIndex;
		m_tab[currentIndex]->setSelect(true);
		m_tab[currentIndex]->setTouchEnabled(false);
		m_tab[preIndex]->setSelect(false);
		m_tab[preIndex]->setTouchEnabled(true);
	}
	if(true)
	{
		this->isInternal=false;
		this->callBack();
	}
}

void IMITab::onTabEvent(CCObject *target, IMI_TouchHandler selector)
{
	m_iTouchBeganListener = target;
	m_ifnTouchBeganSelector = selector;
}

void IMITab::callBack()
{
	if (m_iTouchBeganListener && m_ifnTouchBeganSelector)
	{
		(m_iTouchBeganListener->*m_ifnTouchBeganSelector)(this->currentIndex);
	}
}

void IMITab::changeTab(CCObject* object, CCTouch *pTouch, CCEvent *pEvent)
{
	IMIButton * tempButton=(IMIButton *)object;
	int length=this->m_tab.size();
	for (int i = 0; i < length; i++)
	{
		if(this->m_tab[i]==tempButton)
		{
			this->isInternal=true;
			this->setTab(i);
			break;
		}
	}
}

int IMITab::getTab()
{
	return currentIndex;
}